package com.shijianchen.utils;

import com.shijianchen.projo.SpOtherAdmin;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    //密钥
    private static final String secretString="Zd+kZozTI5OgURtbegh8E6KTPghNNe/tEFwuLxd2UNw=zqzcabcssdddaghjdsasfashbbsswrvasghh";
    //生成安全密钥
    private static final SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));
    public static String generate(SpOtherAdmin spOtherAdmin) throws IllegalAccessException {
        Map<String,Object> claims = new HashMap<>();
        setObjectInfo(spOtherAdmin,claims);
        return Jwts.builder().claims(claims).expiration(new Date(System.currentTimeMillis() + 3600*24*90 * 1000L)).signWith(key, Jwts.SIG.HS256) //算法签名,(密钥，加密算法)
                .compact();
    }
    public static void setObjectInfo(Object obj,Map<String,Object> claims) throws IllegalAccessException {
        Class<?> c = obj.getClass();
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            claims.put(field.getName(),field.get(obj));
        }
    }
    public static Claims decode(String jwt) throws ExpiredJwtException{
        //解析jwt令牌，获取- Payload(有效载荷）
        return Jwts.parser()
                .verifyWith(key) // 传递密钥
                .build()
                .parseSignedClaims(jwt) //传递jwt令牌参数
                .getPayload();
    }
}
